//
// OpenTemplate
// Copyright (c) 2006
// by OpenArrow Software ( http://www.openarrow.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using OpenArrow.Templating.Directives;
using OpenArrow.Utils;
using OpenArrow.Reporting;
using OpenArrow.Templating.Properties;
using System.Security.Permissions;

namespace OpenArrow.Templating.Parsing
{
    /// <summary>
    /// A Template Parser that expects ASP.Net style syntax
    /// </summary>
    /// <remarks>
    /// <para>
    /// The ASP.Net Template Syntax is, as one would expect, derived from the syntax used to create ASP.Net Pages and Controls.
    /// The syntax is simple and if you already know how to use ASP.Net, you don't have much to learn!
    /// </para>
    /// <para>
    /// First, there are 1 or more lines of "Directives" 
    /// (<see cref="OpenArrow.Templating.Directives.IDirective"/>) which provide metadata describing the template and the form
    /// of the generated code. The remainder of the template consists of "Segments" which come in two forms: "Literal Segments",
    /// and "Code Segments". A Literal Segment is dumped as-is into the output when the template is run, literal segments are any text
    /// that is not surrounded by '&lt;%' and '%&gt;'. A Code Segment is code that is executed when the template is run. Code
    /// Segments must make calls to the <see cref="TextWriter"/> object called "output" that automatically exists in all templates in
    /// order to display text. Code Segments come in a few sub types as well, as described below:
    /// <list type="table">
    /// <listheader>
    /// <term>Name (Delimiters)</term>
    /// <description>Purpose</description>
    /// </listheader>
    /// <item>
    /// <term>Output Segment (&lt;%= %&gt;)</term>
    /// <description>
    /// Code in these segments are wrapped in calls to "output.WriteLine()" to aid the developer. 
    /// The contents of an Output Segment must be an expression of type String
    /// </description>
    /// </item>
    /// <item>
    /// <term>Declaration Segment (&lt;%! %&gt;)</term>
    /// <description>
    /// Code in these segments are placed in the body of the class 
    /// (rather than in the <see cref="OpenArrow.Templating.ITemplate.Render(TextWriter, IProgressReporter)"/> method). The contents of a Declaration
    /// Segment must be one or more Type Members (Properties, Fields, Methods, etc.).
    /// </description>
    /// </item>
    /// </list>
    /// </para>
    /// <para>Here is a short example for using template parsers and generators:</para>
    /// <example language="C#">
    /// <code>
    /// using System;
    /// using System.IO;
    /// 
    /// using OpenArrow.Templating.Parsing;
    /// using OpenArrow.Templating.Compilation;
    ///  
    /// public class MyQuickGenerator() 
    /// {
    /// 	public static void Main(string[] args)
    /// 	{
    ///         // Create the parser and generator
    ///         ITemplateParser parser = new ASPNetStyleTemplateParser();
    ///         ITemplateGenerator generator = new StandardTemplateGenerator();
    ///         
    ///         // Open a file stream and stream reader for the template
    ///         FileStream stream = new FileStream("MyTemplate.template", FileAccess.Read);
    ///         StreamReader reader = new StreamReader(stream);
    /// 
    ///         // Parse the template
    ///         TemplateParserResults parserResults = parser.Parse(reader);
    /// 
    ///         // Check for problems
    ///         if(!parserResults.Success)
    ///         {
    ///             Console.WriteLine("Errors Occurred!");
    ///             return;
    ///         }
    /// 
    ///         // Generate a CodeCompileUnit from the template
    ///         TemplateGeneratorResults generatorResults = generator.Generate(parserResults.Output, "MyTemplate.template");
    /// 
    ///         // Check for problems
    ///         if(!parserResults.Success)
    ///         {
    ///             Console.WriteLine("Errors Occurred!");
    ///             return;
    ///         }
    /// 
    ///         // Do what you want with the Compile Unit now!
    ///     }
    /// }
    /// </code>
    /// </example>
    /// <example language="VB">Coming Soon!</example>
    /// <example language="C++">Sorry, no C++ examples are available. Use the C# example as a basis.</example>
    /// </remarks>
    public class AspNetStyleTemplateParser : ITemplateParser
    {
        /// <summary>
        /// Constructs a new <see cref="AspNetStyleTemplateParser"/> objects.
        /// </summary>
        public AspNetStyleTemplateParser() { }

        #region ITemplateParser Members

        /// <summary>
        /// Parses the specified template source file
        /// <seealso cref="OpenArrow.Templating.Parsing.ITemplateParser"/>
        /// </summary>
        /// <param name="input">The input reader to read the template from</param>
        /// <returns>The results of the parsing operation</returns>
        /// <exception cref="OpenArrow.Templating.ActionProblemsException">A large number of errors occurred in the operation and it had to be aborted</exception>
        /// <exception cref="System.IO.IOException">An I/O error occurs</exception>
        /// <exception cref="ArgumentNullException"><paramref name="input"/> is <see langword="null"/></exception>
        public TemplateParserResults Parse(TextReader input)
        {
            return Parse(input, new NullProgressReporter());
        }

        /// <summary>
        /// Parses the specified template source file
        /// <seealso cref="OpenArrow.Templating.Parsing.ITemplateParser"/>
        /// </summary>
        /// <remarks>This method reports its progress to a given progress reporter</remarks>
        /// <param name="input">The input reader to read the template from</param>
        /// <param name="reporter">The progress reporter to report to</param>
        /// <returns>The results of the parsing operation</returns>
        /// <exception cref="OpenArrow.Templating.ActionProblemsException">A large number of errors occurred in the operation and it had to be aborted</exception>
        /// <exception cref="System.IO.IOException">An I/O error occurs</exception>
        /// <exception cref="ArgumentNullException"><paramref name="input"/> is <see langword="null"/></exception>
        public TemplateParserResults Parse(TextReader input, IProgressReporter reporter)
        {
            if (input == null)
                throw new ArgumentNullException(String.Format(Resources.Exception_ArgIsNull, "input"), "input");
            if (reporter == null)
                reporter = new NullProgressReporter();

            TemplateParserResults results = new TemplateParserResults();
            ParsedTemplate template = new ParsedTemplate();

            int lineNo = 1;
            string line = null;
            using (reporter.StartTask(Resources.Task_ParsingDirectives))
            {
                while ((line = input.ReadLine()) != null)
                {
                    // State Changes
                    if (!line.StartsWith("<%@"))
                        break; // Finished reading the directives

                    ReadDirective(line, lineNo, results.Problems, template, reporter);
                    lineNo++;
                }
            }

            if (template.TemplateDirective == null)
                results.Problems.Add(Problem.Error_TemplateDirectiveNotFound());

            using (reporter.StartTask(Resources.Task_ParsingSegments))
            {
                // Parse out the segments
                TextReader reader = new ChainedTextReader(new TextReader[] { new StringReader(line + '\n'), input });
                template.Segments.AddRange(ParseSegments(reader, lineNo, reporter));
                results.Output = template;
                results.Success = (results.Problems.ErrorCount == 0);
            }
            return results;
        }

        #endregion

        #region Private Methods

        private static List<Segment> ParseSegments(TextReader reader, int lineNo, IProgressReporter reporter)
        {
            bool inCode = false;
            int currentStartLine = lineNo;
            List<Segment> segments = new List<Segment>();
            StringBuilder currentSegment = new StringBuilder();

            // Start char-by-char parsing
            int i = -1;
            reporter.StartTask(Resources.Task_ParsingLiteralSegment);
            while ((i = reader.Read()) != -1)
            {
                char c = (char)i;

                if ((!inCode) && (c == '<') && (reader.Peek() == (int)'%'))
                {
                    // Add the new segment
                    AddSegment(segments, currentSegment, true, currentStartLine, lineNo);
                    currentSegment = new StringBuilder();
                    currentStartLine = lineNo;

                    // Consume the '%'
                    reader.Read();

                    // Move to "code-mode"
                    inCode = true;
                    reporter.EndTask();
                    reporter.StartTask(Resources.Task_ParsingCodeSegment);

                    // Read the next char
                    continue;
                }
                else if ((inCode) && (c == '%') && (reader.Peek() == (int)'>'))
                {
                    // Add the new segment
                    AddSegment(segments, currentSegment, false, currentStartLine, lineNo);
                    currentSegment = new StringBuilder();
                    currentStartLine = lineNo;

                    // Consume the '>'
                    reader.Read();

                    // Move to "literal-mode"
                    inCode = false;
                    reporter.EndTask();
                    reporter.StartTask(Resources.Task_ParsingLiteralSegment);

                    // Read the next char
                    continue;
                }

                // TODO: Remove Hard-Coded Line endings
                if (c == '\r') // Mac and Windows (\r and \r\n respectively)
                {
                    lineNo++;
                    if (reader.Peek() == (int)'\n')
                        reader.Read(); // Consume the extra \n on Windows
                    c = '\n';
                }
                else if (c == '\n') // Unix (\n)
                {
                    lineNo++;
                }

                currentSegment.Append(c);
            }
            AddSegment(segments, currentSegment, inCode, currentStartLine, lineNo);
            reporter.EndTask();
            return segments;
        }

        private static void AddSegment(List<Segment> segments, StringBuilder currentSegment, bool isLiteral,
            int startLine, int endLine)
        {
            string segmentContent = currentSegment.ToString();
            if (segmentContent.Length > 0)
                segments.Add(new Segment(isLiteral, segmentContent, startLine, endLine));
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)")]
        private static void ReadDirective(string line, int lineNo, ProblemCollection problems, ParsedTemplate template, IProgressReporter reporter)
        {
            // Sample Directive:    '<%@ Directive Attribute="Value" Attribute="Value" %>'
            string[] directiveArray = StringUtils.StripOuter(line, 3, 2).Trim().Split();

            string directiveName = directiveArray[0];
            int invalidIndex = directiveName.IndexOfAny(new char[] { '=', '"', '\'' });
            if (invalidIndex != -1)
            {
                problems.Add(Problem.Error_InvalidCharacterInDirectiveName(directiveName[invalidIndex], lineNo, invalidIndex + 1));
                return;
            }

            using (reporter.StartTask(String.Format(Resources.Task_ParsingDirective, directiveName)))
            {
                // Read Attributes
                NameValueCollection attributes = new NameValueCollection();
                for (int i = 1; i < directiveArray.Length; i++)
                {
                    string[] attributeArray = directiveArray[i].Split('=');
                    if (attributeArray.Length != 2)
                    {
                        problems.Add(Problem.Error_MultipleEqualsCharactersInAttr(lineNo));
                        return;
                    }

                    attributes[attributeArray[0]] = StringUtils.TakeQuotedValue(attributeArray[1]);
                }

                IDirective directive = DirectiveManager.BuildDirective(directiveName, attributes, lineNo, problems, reporter);
                TemplateDirective templateDir = directive as TemplateDirective;
                if (templateDir != null)
                    template.TemplateDirective = templateDir;
                else
                    template.Directives.Add(directive);
            }
        }

        #endregion

    }
}
